package com.tsd.anon;

import com.baidu.ueditor.ActionEnter;
import com.tsd.common.entity.CommonFile;
import com.tsd.common.service.CommonFileService;
import com.tsd.core.constants.Constants;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.utils.FileUtil;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.HttpUtil;
import com.tsd.core.utils.MapBuilder;
import com.tsd.storage.StorageService;
import io.swagger.annotations.Api;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @ClassName: AnonUeditorController
 * @Description: TODO
 * @Author: Hillpool
 * @Date: 2022/3/15 12:43
 * @Version: 1.0
 */
@Controller
@Scope("prototype")
@RequestMapping("/anon")
@Api(tags = "Ueditor", description = "Ueditor的控制器")
public class AnonUeditorController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AnonUeditorController.class);

    @Resource
    private CommonFileService commonFileService;
    @Resource
    private StorageService storageService;


    @RequestMapping("/ueditorConfig")
    public void ueditorConfig(HttpServletRequest request, HttpServletResponse response, MultipartFile upfile) {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,X_Requested_With");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
            String accountSetSid = HttpUtil.getAccountSet(request);
            DataSourceContextHolder.setDataSourceType(accountSetSid);
            String exec = "";
            String actionType = request.getParameter("action");
            if ("uploadimage".equals(actionType)) {
                // 上传图片、截图工具上传
                exec = uploadFile4UE(request, upfile);
            } else if ("uploadscrawl".equals(actionType)) {
                // 涂鸦图片上传操作
                exec = uploadScrawl4UE(request);
            } else if ("uploadvideo".equals(actionType)) {
                // 上传视频操作
                exec = uploadFile4UE(request, upfile);
            } else if ("uploadfile".equals(actionType)) {
                // 上传文件操作
                exec = uploadFile4UE(request, upfile);
            } else {
                request.setCharacterEncoding("utf-8");
                exec = new ActionEnter(request, rootPath).exec();
            }
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            LOGGER.error("AnonUeditorController#ueditorConfig exception:", e);
        }
    }

    private Map<String, Object> resultMap(String state, CommonFile commonFile) {
        if (commonFile == null) {
            return MapBuilder.builder().put("state", state).build();
        }
        String fileType = FileUtil.getFileType(commonFile.getOriginal_file_name());
        String url = commonFile.getWeb_url();
        if (!StorageService.STORE_TYPE_LOCAL.equals(storageService.getActive())) {
            url = commonFile.getOss_url();
        }
        return MapBuilder.builder()
                .put("state", state)
                .put("original", commonFile.getOriginal_file_name())
                .put("size", commonFile.getFile_len())
                .put("title", commonFile.getOriginal_file_name())
                .put("type", fileType)
                .put("url", url)
                .build();
    }

    private String uploadFile4UE(HttpServletRequest request, MultipartFile file) {
        JSONObject jsonResult;
        if (file == null) {
            jsonResult = new JSONObject(resultMap("文件上传失败", null));
        } else {
            try {
                CommonFile commonFile = commonFileService.addFileInfo4UE(request, file);
                jsonResult = new JSONObject(resultMap("SUCCESS", commonFile));
            } catch (Exception e) {
                LOGGER.warn("AnonUeditorController#uploadImage exception:", e);
                jsonResult = new JSONObject(resultMap("文件上传失败", null));
            }
        }
        return jsonResult.toString();
    }

    private String uploadScrawl4UE(HttpServletRequest request) {
        JSONObject jsonResult;
        try {
            String upfile = request.getParameter("upfile");
            String base64 = "data:image/jpg;base64," + upfile;
            CommonFile commonFile = commonFileService.addBase64FileInfo4UE(request, base64);
            jsonResult = new JSONObject(resultMap("SUCCESS", commonFile));
        } catch (Exception e) {
            LOGGER.warn("AnonUeditorController#uploadImage exception:", e);
            jsonResult = new JSONObject(resultMap("文件上传失败", null));
        }
        return jsonResult.toString();
    }
}
